/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package homedatasender;

import java.util.Iterator;
import javax.jdo.Extent;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Transaction;

/**
 *
 * @author tadas
 */
public class Config {

    protected static Config _Instance = null;
    protected ConfigData _data = null;

    protected Config() {

        PersistenceManagerFactory pmf = PMF.get();

        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx = pm.currentTransaction();
        ConfigData data;

        try {
            tx.begin();
            Extent e = pm.getExtent(ConfigData.class, true);
            Iterator iter = e.iterator();

            if (iter.hasNext()) {
                System.out.println("Found config data");
                Object obj = iter.next();
                if (!(obj instanceof ConfigData)) {
                    throw new RuntimeException("Wrong data");
                }
                data = (ConfigData) (obj);

                this._data = (data);
            } else {
                data = new ConfigData(null, null, null, null, null, null);
                data = pm.makePersistent(data);

                this._data = (data);
                System.out.println("No config found > created new");
            }

            tx.commit();


        } catch (Exception e) {
            System.out.println("Failed to get ConfigData: " + e.getMessage());
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            pm.close();
        }
    }

    public static Config getInstance() {
        if (_Instance == null) {
            _Instance = new Config();
        }
        return _Instance;
    }

    public ConfigData getData() {
        return this._data;
    }
}
